package com.yvchen.yc_system.module.qw.api;

import com.alibaba.fastjson.JSONObject;
import com.yvchen.yc_system.module.qw.config.QwProviderConfig;
import com.yvchen.yc_system.module.qw.config.URL;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpMessageServiceImpl;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.api.impl.WxCpUserServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WQUtil{


    public String getToken(){
        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> param = new HashMap<>();
        param.put("corpid", QwProviderConfig.CORP_ID);
        param.put("corpsecret", QwProviderConfig.PROVIDER_SECRET);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                URL.GET_TOKEN, String.class, param);
        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        String token = jsonObject.get("access_token").toString();
        return responseEntity.getBody();
    }
    public WxCpService wxCpService(){
        WxCpService wxCpService = new WxCpServiceImpl();
        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        config.setCorpSecret(QwProviderConfig.PROVIDER_SECRET);
        config.setCorpId(QwProviderConfig.CORP_ID);
        resetTokenAndJsApi2(wxCpService,config);
        return wxCpService;
    }

    public String getUserIdByPhone(String phone){
        WxCpUserServiceImpl wxCpUserService = new WxCpUserServiceImpl(wxCpService());
        String userId = null;
        try {
            userId = wxCpUserService.getUserId(phone);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        return userId;
    }
    public void resetTokenAndJsApi2(WxCpService wxCpService,WxCpDefaultConfigImpl wxCpDefaultConfig) {
        try {
            wxCpService.setWxCpConfigStorage(wxCpDefaultConfig);
            String accessToken;
            // 获取TOKEN
            accessToken = wxCpService.getAccessToken(false);
            log.info("accessToken:{}", accessToken);
            wxCpDefaultConfig.setAccessToken(accessToken);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

    }

    public void sendToWxCp(String phone) {
        WxCpMessage wxCpMessage = new WxCpMessage();
        // 微信消息对象
        WxCpMessageServiceImpl wxCpMessageService = new WxCpMessageServiceImpl(wxCpService());
        wxCpMessage.setSafe("0");
        wxCpMessage.setAgentId(1000002);
        // 设置消息形式，这里设置为卡片消息
        wxCpMessage.setMsgType(WxConsts.KefuMsgType.TEXTCARD);

        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
        // 设置发送用户
        wxCpMessage.setToUser(getUserIdByPhone(phone));
        // 发送的标题
        wxCpMessage.setTitle("审批通知");
        // 发送内容
        wxCpMessage.setDescription("您有一个待审核任务，请查收"+
                "\n" + "审批名称："+ "任务名称" +
                "\n" + "发起人："+ "发起人姓名" +
                "\n"+ "点击下方跳转");
        // 设置跳转url
        wxCpMessage.setUrl("www.baidu.com");
        wxCpMessage.setBtnTxt("前往");
        try {
            // 发送消息
            WxCpMessageSendResult send = wxCpMessageService.send(wxCpMessage);
            log.info("send result:{}", send);
        } catch (WxErrorException e) {
            log.error("发送信息接口调用出错: {}", e.getMessage());
        }
    }

}
